package com.yantong.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;

import com.yantong.enums.GroupTypeEnum;
import com.yantong.enums.MarketingGroupTypeEnum;
import com.yantong.exception.BDException;
import com.yantong.mapper.MarketingGroupMapper;
import com.yantong.mapper.MarketingGroupSkuMapper;
import com.yantong.mapper.ProductSkuCentreMapper;
import com.yantong.mapper.ProductSpecCentreMapper;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.*;
import com.yantong.service.*;
import com.yantong.utils.DateUtil;
import com.yantong.utils.PageUtils;
import com.yantong.utils.RedisKey;
import com.yantong.utils.ValidateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 支付服务
 *
 * @author kanghaixin
 * @date 2018/9/29.9:50
 */
@Service
public class MarketingGroupServiceImpl implements MarketingGroupService {

	private static Logger logger = LoggerFactory.getLogger(MarketingGroupServiceImpl.class);

	@Autowired
	private MarketingGroupMapper marketingGroupMapper;

	@Autowired
	private MarketingGroupSkuMapper marketingGroupSkuMapper;

	@Autowired
	@Lazy
	private ProductCentreService productCentreService;

	@Autowired
	@Lazy
	private OrderService orderService;

	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private ProductSpecCentreMapper specCentreMapper;
	@Autowired
	private ProductSkuCentreMapper productSkuCentreMapper;
	@Autowired
	private TicketService ticketService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private ActivityService activityService;

	@Override
	public int saveMarketingGroup(MarketingGroup marketingGroup) {
		Long productId = marketingGroup.getProductId();
		if(MarketingGroupTypeEnum.ORDINARY.getCode().equals(marketingGroup.getMarketingGroupType())){
			ProductCentre productCentre = productCentreService.getProductCentre(productId);
			if (null == productCentre) {
				throw new BDException("ID为【" + marketingGroup.getProductId() + "】的产品不存在");
			}
			marketingGroup.setTicketIds(this.ticketDealWith(marketingGroup, productCentre));


			if (marketingGroup.getTeamId() == null) {//teamId不存在，则从产品中获取
				marketingGroup.setTeamId(productCentre.getLiansuoid());
			}
			if (marketingGroup.getStock() == null || marketingGroup.getStock() == 0 || marketingGroup.getStock() < 0) {
				throw new BDException("【" + marketingGroup.getProductName() + "】库存不足!");
			}
			//修改后的库存，不能比已经拼团完成的库存小
			Integer changStock = marketingGroup.getStock() == null ? 0 : marketingGroup.getStock();

			List<MarketingGroupSku> list = marketingGroup.getSkus();

			//没有多规格的产品
			if (productCentre.getHasoption() == 0) {
				if (productCentre.getTotal() < changStock) {
					throw new BDException("参与拼团数量不能大于商品总库存");
				}
				//更新产品的库存
				productCentre.setTotal(productCentre.getTotal() - changStock);
				productCentreService.updateProductCenter(productCentre);
			}
			//有多规格的产品，需要校验多规格的产品库存数量
			else if (productCentre.getHasoption() == 1) {

				if (ValidateUtil.isNotEmptyCollection(list)) {
					for (MarketingGroupSku marketingGroupSku : list) {
						if (marketingGroupSku.getStock() == null || marketingGroupSku.getStock() == 0) {
							throw new BDException("【" + marketingGroupSku.getTitle() + "】库存不足!");
						}
						ProductSkuCentre productSkuCentre = productCentreService.getSkuByKey(marketingGroupSku.getSkuId());
						//库存
						if (null == productSkuCentre.getStock() || productSkuCentre.getStock() < marketingGroupSku.getStock()) {
							throw new BDException("【" + marketingGroupSku.getTitle() + "】库存不足，不能超过" + productSkuCentre.getStock());
						}
						//库存通过校验，则将库存更新
						productSkuCentre.setStock(productSkuCentre.getStock() - marketingGroupSku.getStock());
						productCentreService.updateProductSkuCenter(productSkuCentre);
					}

					marketingGroupSkuMapper.deleteByProductId(marketingGroup.getId());
					int total = 0;
					for (MarketingGroupSku item : list) {
						item.setProductId(marketingGroup.getId());
						item.setSkuId(item.getSkuId() == 0 ? item.getId() : item.getSkuId());

						total = total + item.getStock();
					}
					if (total != marketingGroup.getStock()) {
						//设置库存
						marketingGroup.setStock(total);
						MarketingGroupExample example = new MarketingGroupExample();
						example.createCriteria().andIdEqualTo(marketingGroup.getId());
						marketingGroupMapper.updateByExample(marketingGroup, example);
					}
				}
			}
			for (MarketingGroupSku item : list) {
				item.setProductId(marketingGroup.getId());
				marketingGroupSkuMapper.insert(item);
			}
		}else{
			Activity Activity = activityService.getActivityById(productId);
			if (null == Activity) {
				throw new BDException("ID为【" + marketingGroup.getProductId() + "】的大礼包不存在");
			}
		}
		int count = marketingGroupMapper.insertSelective(marketingGroup);

		return count;
	}

	//拼团优惠券配置处理
	private String ticketDealWith(MarketingGroup marketingGroup, ProductCentre productCentre) {
		String json = "";
		Long teamId = productCentre.getLiansuoid();
		List<TicketDTO> list = new ArrayList();
		if (GroupTypeEnum.SNAP_UP.getCode().equals(marketingGroup.getType())
				&& marketingGroup.getIsCoupons() != null && marketingGroup.getIsCoupons() == 1
				&& ValidateUtil.isNotEmptyCollection(marketingGroup.getTicketList())) {
			boolean bol = false;
			for (TicketDTO ticketDTO : marketingGroup.getTicketList()) {
				if (ticketDTO != null) {
					bol = true;
					break;
				}
			}
			if (!bol) {
				throw new BDException("请配置优惠券信息");
			}
			for (TicketDTO ticketDTO : marketingGroup.getTicketList()) {
				if (ticketDTO != null) {
					Ticket ticket = ticketService.getByKey(ticketDTO.getId());
					list.add(ticketDTO);
					if (teamId != null && !teamId.equals(ticket.getTeamId()) && MarketingGroupTypeEnum.ORDINARY.getCode().equals(marketingGroup.getMarketingGroupType())) {
						throw new BDException("优惠券" + ticket.getTicketName() + "与拼团商品所属门店不同");
					}
				}
			}
			json = JSONObject.toJSONString(list);
		}
		return json;
	}

	@Override
	public int updateMarketingGroup(MarketingGroup marketingGroup) {
		//查询老的拼团商品信息
		MarketingGroup marketingGroupCurrent = marketingGroupMapper.getMarketingGroupById(marketingGroup.getId());
		if(MarketingGroupTypeEnum.ORDINARY.getCode().equals(marketingGroup.getMarketingGroupType())) {
			Long productId = marketingGroup.getProductId();
			ProductCentre productCentre = productCentreService.getProductCentre(productId);

			if (null == productCentre) {
				throw new BDException("ID为【" + marketingGroup.getProductId() + "】的产品不存在");
			}

			marketingGroup.setTicketIds(this.ticketDealWith(marketingGroup, productCentre));

			if (marketingGroup.getTeamId() == null) {//teamId不存在，则从产品中获取
				marketingGroup.setTeamId(productCentre.getLiansuoid());
			}

			//修改后的库存，不能比已经拼团完成的库存小
			Integer changStock = marketingGroup.getStock() == null ? 0 : marketingGroup.getStock();
//        //获取此阶段内，已经拼团的总数量
//        Integer spellGroupedCount = orderService.getSpellGroupCountByProductId(marketingGroup.getProductId(), marketingGroup.getStartTime(), marketingGroup.getEndTime());
//        if (changStock > 0 && changStock < spellGroupedCount) {
//            throw new BDException("修改的数量不能小于已经拼团的商品数量");
//        }

			//没有多规格的产品
			if (productCentre.getHasoption() == 0) {

				if (productCentre.getTotal() < changStock) {
					throw new BDException("修改的参与拼团数量不能大于商品总库存");
				}
				//更新产品的库存
				productCentre.setTotal(productCentre.getTotal() - changStock);
				productCentreService.updateProductCenter(productCentre);
				marketingGroup.setStock(marketingGroupCurrent.getStock() + changStock);
			}
			//有多规格的产品，需要校验多规格的产品库存数量
			else if (productCentre.getHasoption() == 1) {
				List<MarketingGroupSku> list = marketingGroup.getSkus();
				if (ValidateUtil.isNotEmptyCollection(list)) {
					for (MarketingGroupSku marketingGroupSku : list) {
						if (marketingGroupSku.getStock() == null || marketingGroupSku.getStock() == 0) {
							throw new BDException("【" + marketingGroupSku.getTitle() + "】库存不足!");
						}

						Long skuId = marketingGroupSku.getSkuId() == 0 ? marketingGroupSku.getId() : marketingGroupSku.getSkuId();
						ProductSkuCentre productSkuCentre = productCentreService.getSkuByKey(skuId);

						//库存
//                    if (null == productSkuCentre.getStock() || productSkuCentre.getStock() < marketingGroupSku.getStock()) {
//                        throw new BDException("【" + marketingGroupSku.getTitle() + "】库存不足，不能超过" + productSkuCentre.getStock());
//                    }

						MarketingGroupSku marketingGroupSkuCurrent = marketingGroupSkuMapper.getMarketingGroupSkuByActivityId(marketingGroupSku.getProductId(), marketingGroupSku.getSkuId());
						int diff = 0;
						if (marketingGroupSkuCurrent == null) {//不存在记录，则说明当前是新增的规格拼团记录
							diff = marketingGroupSku.getStock();
						} else {//已经存在的，则说明是修改已经存在的规格记录
							diff = marketingGroupSku.getStock() - marketingGroupSkuCurrent.getStock();
						}
						//新输入的纪录比当前的记录值大，说明是新增，新增的数额，不能大于目前商品的库存
						if (diff > 0 && (null == productSkuCentre.getStock() || productSkuCentre.getStock() < diff)) {
							throw new BDException("【" + marketingGroupSku.getTitle() + "】库存不足，不能超过" + productSkuCentre.getStock());
						}

						//库存通过校验，则将库存更新
						productSkuCentre.setStock(productSkuCentre.getStock() - diff);
						productCentreService.updateProductSkuCenter(productSkuCentre);
					}

					int total = 0;
					marketingGroupSkuMapper.deleteByProductId(marketingGroup.getId());
					for (MarketingGroupSku item : list) {
						item.setProductId(marketingGroup.getId());
						item.setSkuId(item.getSkuId() == 0 ? item.getId() : item.getSkuId());
						marketingGroupSkuMapper.insert(item);
						total = total + item.getStock();
					}
					//设置库存
					marketingGroup.setStock(total);
				}
			}

		}else{
			Activity Activity = activityService.getActivityById(marketingGroup.getProductId());
			if (null == Activity) {
				throw new BDException("ID为【" + marketingGroup.getProductId() + "】的大礼包不存在");
			}
		}
		MarketingGroupExample example = new MarketingGroupExample();
		example.createCriteria().andIdEqualTo(marketingGroup.getId());
		int count = marketingGroupMapper.updateByExampleSelective(marketingGroup, example);

		//抢购拼团改为随机拼将相关数据清空
		if(GroupTypeEnum.SNAP_UP.getCode().equals(marketingGroupCurrent.getType())
				&& GroupTypeEnum.RANDOM.getCode().equals(marketingGroup.getType())){
			marketingGroupMapper.updateIsNull(marketingGroup.getId());
		}
		return count;
	}


	@Override
	public PageUtils<MarketingGroup> listAllGroup(int offset, int limit, MarketingGroup vo) {
		PageUtils<MarketingGroup> pageUtils = new PageUtils<>();
		MarketingGroupExample example = new MarketingGroupExample();
		MarketingGroupExample.Criteria criteria = example.createCriteria();
		if (StringUtils.isNotBlank(vo.getProductName())) {
			criteria.andProductNameLike('%' + vo.getProductName() + "%");
		}
		if (StringUtils.isNotBlank(vo.getActivityName())) {
			criteria.andActivityNameLike('%' + vo.getActivityName() + "%");
		}
		if (vo.getCentreId() != null && vo.getCentreId() > 0L) {
			criteria.andCentreIdEqualTo(vo.getCentreId());
		}
		if (vo.getTeamId() != null && vo.getTeamId() > 0L) {
			criteria.andTeamIdEqualTo(vo.getTeamId());
		}
		Long total = marketingGroupMapper.countByExample(example);
		if (total > 0) {
			pageUtils.setTotal(Integer.parseInt(total + ""));
			List<MarketingGroup> list = marketingGroupMapper.selectByExample(example, new RowBounds(offset, limit));
			for ( MarketingGroup m : list ) {
				Member member = memberService.getByKey(m.getTeamId());
				if(member != null){
					m.setTeamName(member.gettXiaoqu());
				}

			}
			pageUtils.setRows(list);
		}
		return pageUtils;
	}

	@Override
	public PageUtils<ApiMarketingGroupResVo> listAllGroupForFront(int offset, int limit, ApiMarketingGroupReqVo vo) {
		PageUtils<ApiMarketingGroupResVo> pageUtils = new PageUtils<>();
		Map<String, Object> param = new HashMap<>();
//        MarketingGroupExample example = new MarketingGroupExample();
//        Criteria criteria = example.createCriteria();
		if (vo.getCentreId() != null) {
//            criteria.andCentreIdEqualTo(vo.getCentreId());
			param.put("centreId", vo.getCentreId());
//			if(vo.getHotFlag()!= null && vo.getHotFlag() == 1){
//				Member member = memberService.selectHeadOffice(vo.getCentreId());
//				if(member != null){
//					param.put("teamId", member.getId());
//				}
//			}
		}

		if (vo.getTeamId() != null) {
//            criteria.andTeamIdEqualTo(vo.getLiansuoid());
			if(!param.containsKey("teamId")){
				param.put("teamId", vo.getTeamId());
			}
		}

		if (vo.getLiansuoid() != null) {
//            criteria.andTeamIdEqualTo(vo.getLiansuoid());
			if(!param.containsKey("teamId")){
				param.put("teamId", vo.getLiansuoid());
			}
		}

		if (vo.getShowType() != null) {
			param.put("showType", vo.getShowType());
		}

		if (vo.getType() != null) {
			param.put("type", vo.getType());
		}

		if (vo.getIsRecommend() != null) {
			param.put("isRecommend", vo.getIsRecommend());
		}


		if (vo.getMarketingGroupType() != null) {
			param.put("marketingGroupType", vo.getMarketingGroupType());
		}


		param.put("todayDate", DateUtil.convertDateToStr(new Date(), DateUtil.yyyy_MM_dd));
		param.put("tomorrowDate", DateUtil.getAddDayDateStr(new Date(), 1));

		//排序
		List<String> orderList = new ArrayList<>();
		orderList.add("group_price");
		orderList.add("sales");

		if ( orderList.contains(vo.getSidx()) ) {
			if (StringUtil.isNotEmpty(vo.getOrder())) {
				param.put("orderByClause",vo.getSidx()+" desc");
			} else {
				param.put("orderByClause",vo.getSidx());
			}
		}
		//排序
//        if (StringUtil.isNotEmpty(vo.getSidx())) {
//            if (vo.getSidx().equals("marketprice")) {//价格排序
//
//                if (StringUtil.isNotEmpty(vo.getOrder())) {
//                    example.setOrderByClause("max_price desc");
//                } else {
//                    example.setOrderByClause("min_price");
//                }
//            } else if (vo.getSidx().equals("salesreal")) {
//
//            } else if (vo.getSidx().equals("isnew")) {
//                if (StringUtil.isNotEmpty(vo.getOrder())) {
//                    example.setOrderByClause("start_time desc");
//                } else {
//                    example.setOrderByClause("start_time");
//                }
//            }
//        }
//        //价格区间筛选
//        if (vo.getMinPrice() != null && vo.getMinPrice().compareTo(BigDecimal.ZERO) == 1 && vo.getMaxPrice() != null && vo.getMaxPrice().compareTo(BigDecimal.ZERO) == 1) {
//            criteria.andGroupPriceBetween(vo.getMinPrice(), vo.getMaxPrice());
//        }
		List<ApiMarketingGroupResVo> groupResVoList = new ArrayList<>();
//        Long total = marketingGroupMapper.countByExample(example);
		int total = marketingGroupMapper.count(param);
		if (total > 0) {
			pageUtils.setTotal(Integer.parseInt(total + ""));
			List<MarketingGroup> list = marketingGroupMapper.selectByCondition(param, new RowBounds(offset, limit));
//            List<MarketingGroup> list = marketingGroupMapper.selectByExample(example, new RowBounds(offset, limit));
			if (list != null) {
				list.stream().forEach(item -> {

					ApiMarketingGroupResVo groupResVo = new ApiMarketingGroupResVo();
					ProductCentre productCentre = null;
					Activity activity = null;
					if(MarketingGroupTypeEnum.GIFT_BAG.getCode().equals(item.getMarketingGroupType())){
						activity =  activityService.getActivityById(item.getProductId());
						if (activity == null) {
							return;
						}
						BeanUtils.copyProperties(activity, groupResVo);
						groupResVo.setTitle(activity.getActivityName());
						groupResVo.setProductprice(activity.getActivityPrice());
					}else{
						productCentre = productCentreService.getByKeyWithCache(item.getProductId());
						if (productCentre == null) {
							return;
						}
						BeanUtils.copyProperties(productCentre, groupResVo);
					}
					groupResVo.setId(item.getId());
					groupResVo.setType(item.getType());
					groupResVo.setProductId(item.getProductId());
					groupResVo.setTimestart(item.getStartTime());
					groupResVo.setTimeend(item.getEndTime());
					groupResVo.setIsSpellgroup(1);
					groupResVo.setIsmiaosha(0);
					groupResVo.setIsnew(0);
					groupResVo.setIshot(0);
					groupResVo.setIsrecommand(0);
					groupResVo.setTotal(item.getStock());
					groupResVo.setSalesreal(item.getSales());
					groupResVo.setWinningNumber(item.getWinningNumber());
					groupResVo.setNeedJoinGroupNum(item.getNeedJoinGroupNum());
					groupResVo.setMarketingGroupType(item.getMarketingGroupType());
					groupResVo.setVipPrice(item.getVipPrice());

					MarketingGroupSkuExample skuExample = new MarketingGroupSkuExample();
					skuExample.createCriteria().andProductCentreIdEqualTo(item.getProductId());
					List<MarketingGroupSku> skus = marketingGroupSkuMapper.selectByExample(skuExample);
					if (skus != null) {
						List<ProductSkuCentre> skuList = new ArrayList<>();
						skus.stream().forEach(skuitem -> {
							ProductSkuCentre skuCentre = new ProductSkuCentre();
							BeanUtils.copyProperties(skuitem, skuCentre);
							skuCentre.setMarketprice(skuitem.getGroupPrice());
							skuCentre.setVipPrice(skuitem.getVipPrice());
							skuList.add(skuCentre);
						});
						groupResVo.setSkus(skuList);
					}
					groupResVo.setMarketprice(item.getGroupPrice());
					groupResVo.setSpellgroupnum(item.getNeedJoinGroupNum());
					groupResVo.setIsRecommend(item.getIsRecommend());

					groupResVoList.add(groupResVo);
				});
			}
			pageUtils.setRows(groupResVoList);


		} else {
			pageUtils.setRows(groupResVoList);
		}
		return pageUtils;
	}

//    @Override
//    public MarketingGroup getMarketingGroupByProductId(Long productId) {
//        return marketingGroupMapper.getMarketingGroupByProductId(productId);
//    }

	@Override
	public MarketingGroup getMarketingGroupById(Long id) {
		return marketingGroupMapper.getMarketingGroupById(id);
	}

	@Override
	public ApiMarketingGroupResVo getMarketingGroupDetail(Long memberId, Long activityId, Long orderId) {
		MarketingGroup marketingGroup = this.getMarketingGroupById(activityId);


		if (marketingGroup == null) {
			throw new BDException("抱歉，活动已经下架了");
		}

		ApiMarketingGroupResVo groupResVo = new ApiMarketingGroupResVo();
		Activity activity = null;
		if(MarketingGroupTypeEnum.ORDINARY.getCode().equals(marketingGroup.getMarketingGroupType())){
			ProductCentre productCentre = productCentreService.getByKeyWithCache(marketingGroup.getProductId());
			if (productCentre == null) {
				throw new BDException("抱歉，活动已经下架了");
			}
			BeanUtils.copyProperties(productCentre, groupResVo);
		}else{
			activity = activityService.getActivityById(marketingGroup.getProductId());
			if (activity == null) {
				throw new BDException("抱歉，活动已经下架了");
			}
		}
		//商品属性
		ProductCentreAttribute productCentreAttribute = productCentreService.getProductCentreAttributeByPcId(marketingGroup.getProductId());
		groupResVo.setProductCentreAttribute(productCentreAttribute);

		groupResVo.setIsSpellgroup(1);
		groupResVo.setIsmiaosha(0);
		groupResVo.setIsnew(0);
		groupResVo.setIshot(0);
		groupResVo.setIsrecommand(0);
		groupResVo.setType(marketingGroup.getType());
		groupResVo.setWinningNumber(marketingGroup.getWinningNumber());
		groupResVo.setId(activityId);
		groupResVo.setTimestart(marketingGroup.getStartTime());
		groupResVo.setTimeend(marketingGroup.getEndTime());
		groupResVo.setProductId(marketingGroup.getProductId());
		groupResVo.setVipPrice(marketingGroup.getVipPrice());
		groupResVo.setMarketingGroupType(marketingGroup.getMarketingGroupType());
		groupResVo.setPtDescription(marketingGroup.getDescription()); //拼团大礼包详情
		groupResVo.setNeedJoinGroupNum(marketingGroup.getNeedJoinGroupNum());
		groupResVo.setGroupPrice(marketingGroup.getGroupPrice());
		if(activity!=null){
			groupResVo.setThumb(activity.getThumb());
			groupResVo.setProductprice(activity.getActivityPrice());
			groupResVo.setTitle(activity.getActivityName());
		}

		Integer needJoinGroupNum = marketingGroup.getNeedJoinGroupNum() == null ? 0 : marketingGroup.getNeedJoinGroupNum();
		groupResVo.setSpellgroupnum(needJoinGroupNum);
		MarketingGroupSkuExample skuExample = new MarketingGroupSkuExample();
		skuExample.createCriteria().andProductIdEqualTo(marketingGroup.getId());
		List<MarketingGroupSku> skus = marketingGroupSkuMapper.selectByExample(skuExample);

		List<String> spaceItemIdList = new ArrayList<>();
		if (ValidateUtil.isNotEmptyCollection(skus)) {
			int total = 0;
			List<ProductSkuCentre> skuList = new ArrayList<>();
			for (MarketingGroupSku skuitem : skus) {
				ProductSkuCentre skuCentre = new ProductSkuCentre();
				BeanUtils.copyProperties(skuitem, skuCentre);
				skuCentre.setMarketprice(skuitem.getGroupPrice());
				skuList.add(skuCentre);
				total = total + skuitem.getStock();

				String[] strs = skuitem.getSpecs().split("_");
				Collections.addAll(spaceItemIdList, strs);
			}
			groupResVo.setTotal(total);
			groupResVo.setSkus(skuList);
			groupResVo.setHasoption(1);
		}
		//单一规格的，直接展示库存
		else {
			groupResVo.setTotal(marketingGroup.getStock());
		}
		groupResVo.setIsSpellgroup(1);
		groupResVo.setMarketprice(marketingGroup.getGroupPrice());

		groupResVo.setInitiatorCommission(marketingGroup.getInitiatorCommission());
		groupResVo.setGeneralMemberCommission(marketingGroup.getGeneralMemberCommission());

		//先设置为正常
		groupResVo.setSpellgroupStu(1);
		//拼团订单数据
		List<SpellGroupOrdVo> sgOrds = null;
		//订单详情
		if (orderId == null) {
			SpellGroupOrdVo vo = new SpellGroupOrdVo();
			vo.setProductId(marketingGroup.getProductId());//拼团商品id
			vo.setPeoplenum(marketingGroup.getNeedJoinGroupNum());//拼团商品人数
			vo.setActivityId(activityId);
			sgOrds = orderService.getSpellGroupOrd(vo);
		} else {
			//分享拼团的商品详情
			sgOrds = orderService.getSpellGroupOrdById(orderId);
			SpellGroupOrdVo vo = new SpellGroupOrdVo();
			vo.setMid(memberId);
			vo.setSgorderId(orderId);
			vo.setActivityId(activityId);
			//查询是否参团
			List<Order> list = orderService.getSpellGroupOrdByMid(vo);
			if (CollectionUtils.isNotEmpty(list)) {
				groupResVo.setIsJoin(1);//已参加
			} else {
				groupResVo.setIsJoin(2);//未参加
			}
			if (!sgOrds.isEmpty()) {
				//已结束
				if (new Date().compareTo(marketingGroup.getEndTime()) == 1) {
					groupResVo.setSpellgroupStu(2);
					//已满团
				} else if (sgOrds.get(0).getSpellgroupnum() != null && sgOrds.get(0).getSpellgroupnum() >= marketingGroup.getNeedJoinGroupNum()) {
					groupResVo.setSpellgroupStu(3);
				}
			}
		}
		for (SpellGroupOrdVo spellGroupOrdVo : sgOrds) {
			OrderProductDetailVo orderProductVo = new OrderProductDetailVo();
			orderProductVo.setId(spellGroupOrdVo.getOrderid());
			//查找参与拼团订单的头像
			List<SpellGroupOrdVo> heads = orderService.getGroupOrdHead(orderProductVo);
			if (CollectionUtils.isNotEmpty(heads)) {
				spellGroupOrdVo.setAvatars(heads);
			}
			if (spellGroupOrdVo.getSkuId() != null) {
				List<ProductSkuCentre> skusResult = new ArrayList<>();
				ProductSkuCentre productSkuCentre = productSkuCentreMapper.selectByPrimaryKey(spellGroupOrdVo.getSkuId());
				spellGroupOrdVo.setProductSkuCentre(productSkuCentre);
			}
			if (spellGroupOrdVo.getSkuId() != null && spellGroupOrdVo.getActivityId() != null) {
				MarketingGroupSku marketingGroupSku = marketingGroupSkuMapper.getMarketingGroupSkuByActivityId(spellGroupOrdVo.getActivityId(),spellGroupOrdVo.getSkuId());
				spellGroupOrdVo.setMarketingGroupSku(marketingGroupSku);
			}

		}

		//拼团商品订单 在拼团中的
		groupResVo.setSpellGroupOrdS(sgOrds);
//        groupResVo.setSales(marketingGroup.getSales());
		groupResVo.setSalesreal(marketingGroup.getSales());


		//过滤规格项
		List<ProductSpecCentre> productSpecList = specCentreMapper.getByProductId(marketingGroup.getProductId(), null);
		List<ProductSpecCentre> productSpecListResult = new ArrayList<>();
		productSpecList.forEach(productSpecCentre -> {
			List<ProductSpecItemCentre> specItemList = new ArrayList<>();
			productSpecCentre.getSpecItemList().forEach(specItem -> {
				if (spaceItemIdList.contains(specItem.getId().toString())) {
					specItemList.add(specItem);
				}
			});
			if (ValidateUtil.isNotEmptyCollection(specItemList)) {
				productSpecCentre.setSpecItemList(specItemList);
				productSpecListResult.add(productSpecCentre);
			}
		});
		//规格项
		groupResVo.setProductSpecList(productSpecListResult);

		return groupResVo;
	}


	@Transactional(rollbackFor = Exception.class)
	@Override
	public void removeGroup(Long id) {
		MarketingGroup marketingGroup = marketingGroupMapper.getMarketingGroupById(id);
		if (marketingGroup == null) {
			throw new BDException("拼团活动不存在");
		}
		ProductCentre productCentre = productCentreService.getProductCentre(marketingGroup.getProductId());
//		if (null == productCentre) {
//			throw new BDException("拼团活动异常，请联系管理员");
//		}

		//没有多规格，库存直接回补即可
		if ( productCentre != null && (productCentre.getHasoption() == 0 || productCentre.getHasoption() == null)) {
			productCentre.setTotal(productCentre.getTotal() + marketingGroup.getStock());
			productCentreService.updateProductCenter(productCentre);
		}
		//多规格的产品，修改多规格的库存
		else {
			MarketingGroupSkuExample example = new MarketingGroupSkuExample();
			example.createCriteria().andProductCentreIdEqualTo(marketingGroup.getProductId());
			List<MarketingGroupSku> marketingGroupSkus = marketingGroupSkuMapper.selectByExample(example);
			if (ValidateUtil.isNotEmptyCollection(marketingGroupSkus)) {
				for (MarketingGroupSku marketingGroupSku : marketingGroupSkus) {
					ProductSkuCentre productSkuCentre = productCentreService.getSkuByKey(marketingGroupSku.getSkuId());
					if (null != productSkuCentre) {
						productSkuCentre.setStock(productSkuCentre.getStock() + marketingGroupSku.getStock());
						productCentreService.updateProductSkuCenter(productSkuCentre);
					}
				}
			}
			marketingGroupSkuMapper.deleteByProductId(marketingGroup.getId());
		}

		MarketingGroupExample example = new MarketingGroupExample();
		example.createCriteria().andIdEqualTo(id);
		marketingGroupMapper.deleteByExample(example);
	}

	@Override
	public MarketingGroupSku getMarketingGroupSkuByActivityId(Long activityId, Long skuId) {
		return marketingGroupSkuMapper.getMarketingGroupSkuByActivityId(activityId, skuId);
	}

	@Override
	public List<MarketingGroupSku> listMarketingGroupSkuByProductId(Long productCentreId) {
		MarketingGroupSkuExample seckillExample = new MarketingGroupSkuExample();
		seckillExample.createCriteria().andProductCentreIdEqualTo(productCentreId);

		return marketingGroupSkuMapper.selectByExample(seckillExample);
	}

	@Override
	public int changeStock(Integer total, Long activityId) {
		return marketingGroupMapper.changeStock(total, activityId);
	}

	@Override
	public int changeSkuStock(Integer total, Long activityId, Long skuId) {
		changeStock(total, activityId);
		return marketingGroupSkuMapper.changeStock(total, activityId, skuId);
	}

	@Override
	public int changeSkuStockAlone(Integer total, Long activityId, Long skuId) {
		return marketingGroupSkuMapper.changeStock(total, activityId, skuId);
	}

	@Override
	public MarketingGroupSku getSkuBySpecs(Long activityId, String specs) {
		return marketingGroupSkuMapper.getSkuBySpecs(activityId, specs);
	}

	@Override
	public List<MarketingGroupSku> getSkuByActivityId(Long activityId) {
		return marketingGroupSkuMapper.getSkuByActivityId(activityId);
	}

	@Override
	public List<MarketingGroup> getMarketingGroupByProductId(Long productId) {
		return marketingGroupSkuMapper.getMarketingGroupByProductId(productId);
	}

	@Override
	public MarketingGroupSku getSkuBySkuId(Long activityId, Long skuId) {
		return marketingGroupSkuMapper.getMarketingGroupSkuByActivityId(activityId, skuId);
	}

}
